//
//  HZL_FirstMainViewController.m
//  B_Project
//
//  Created by 胡佳俊 on 15/11/23.
//  Copyright © 2015年 HZL. All rights reserved.
//

#import "HZL_FirstMainViewController.h"
#import "HZL_NetworkingHandle.h"
#import "HZL_StoreTableViewCell.h"
#import "HZL_StoreDetailViewController.h"
#import "AppDelegate.h"
#import "HZL_LocationCollectionViewCell.h"
#import "HZL_StateViewController.h"
#import "RESideMenu.h"
@interface HZL_FirstMainViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, retain) UIView *location;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *locationData;
@property (nonatomic, retain) NSString *city;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, copy) NSString *body;
// 刷新
@property (nonatomic, assign) NSInteger MJI;
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, retain) MJRefreshAutoStateFooter *footer;
@end

@implementation HZL_FirstMainViewController
#pragma mark - 网络状态判断
- (void)netJudge
{
    //网络状态判断
    [HZL_NetworkingHandle networkReachabilityStatus:^(id r) {
        //判断网络是否有wifi 如果没有WiFi建议在WiFi下使用
        if (![r isEqualToNumber:@2]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前是非WiFi环境 建议在WiFi下使用" preferredStyle:UIAlertControllerStyleAlert];
            //获取app的根视图
            UIWindow *app = [UIApplication sharedApplication].keyWindow;
            [app.rootViewController presentViewController:alert animated:YES completion:nil];
            //提示在一秒后消失
            [self performSelector:@selector(removeAlert) withObject:alert afterDelay:2];
        }
    }];
}
#pragma mark - 移除WiFi提示
- (void)removeAlert
{
    //alertView消失
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidAppear:(BOOL)animated
{
//    self.hidesBottomBarWhenPushed = NO;
//    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.tabBarController.tabBar.hidden = NO;
    
    // 注册通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changeCityButton:) name:@"changeCityButton" object:nil];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"厦门" style:UIBarButtonItemStylePlain target:self action:@selector(pushView)];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-liebiao"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    self.dataArr = [NSMutableArray array];

    [self getLocationData];
//    [self getData];
    [self creatTableView];
    [self netJudge];
    [self loadMBProgress];
    
}


- (void)changeCityButton:(NSNotification *)note
{
    self.navigationItem.rightBarButtonItem.title = note.object;
}
#pragma mark - 弹出城市页面
-(void)pushView
{
    // 城市页面
    self.location = [[UIView alloc] initWithFrame:CGRectMake(0, VIEW_HEIGHT, VIEW_WIDTH, VIEW_HEIGHT)];
    self.location.backgroundColor = [UIColor blackColor];
    self.location.alpha = 0.85;
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [app.window addSubview:self.location];

    // 返回按钮
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(20, 30, 20, 20);
    [back setImage:[UIImage imageNamed:@"iconfont-cha@2x"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.location addSubview:back];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, VIEW_HEIGHT, VIEW_WIDTH, 30)];
    label.font = [UIFont boldSystemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"我们正在努力开发更多城市哦!";
    label.textColor = [UIColor whiteColor];
    [self.location addSubview:label];
    
    // 创建collectionView
    [self createCollectionView];
    // 动画 视图上来
    _y = VIEW_HEIGHT;
    [UIView animateWithDuration:0.5 animations:^{
        _y=_y+1;
        self.location.frame = CGRectMake(0, _y-VIEW_HEIGHT, VIEW_WIDTH, VIEW_HEIGHT + 49);
    }];
}

#pragma mark - 创建城市collectionView
- (void )createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((VIEW_WIDTH -60) / 4, (VIEW_WIDTH -60) / 4);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 30, 10);
    
    //创建collectionView
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 130, VIEW_WIDTH , 400) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.location addSubview:self.collectionView];
    //collectionView 注册cell
    [self.collectionView registerClass:[HZL_LocationCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    
}
#pragma mark - 获取城市数据
- (void)getLocationData
{
    [HZL_NetworkingHandle requestPOSTWithURl:@"http://www.molyo.com/mArea/getCityListV1_7 " body:@"enableFlag=1" completion:^(id result) {
        NSMutableArray *tempArr = result[@"body"][@"list"];
        self.locationData = [HZL_StoreModel transformWithArray:tempArr];
        [self.collectionView reloadData];
    }];
}
#pragma mark - 城市collectionView方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.locationData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZL_LocationCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    // 2.设置cell
    cell.model = self.locationData[indexPath.item];
    return cell;
}
#pragma mark - 城市collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.index = indexPath.item;
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeCity" object:[self.locationData[indexPath.item] iD] userInfo:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeCityButton" object:[self.locationData[indexPath.item] name] userInfo:nil];
    
    // 单例
    [[NSUserDefaults standardUserDefaults]setObject:[self.locationData[indexPath.item] iD] forKey:@"city"];
    [self back];
}
#pragma mark - 返回
- (void)back
{
    // 视图下去
    _y=0;
    [UIView animateWithDuration:0.5 animations:^{
        _y=_y-1;
        self.location.frame = CGRectMake(0, _y +VIEW_HEIGHT +49, VIEW_WIDTH, VIEW_HEIGHT );
    }];
}

#pragma mark - 创建tableView
- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT- 49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:self.tableView];
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isRefresh = YES;
        self.MJI = 1;
        [self getData];
    }];
    [self.tableView.mj_header beginRefreshing];

    // 上拉加载
    self.footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        self.isRefresh = NO;
        self.MJI ++;
        [self getData];
    }];
    self.tableView.mj_footer = self.footer;

}
- (void)changeCity:(NSNotification *)note
{
    self.body = note.object;
    [self.tableView.mj_header beginRefreshing];

    [self getData];
}
#pragma mark - 获取tableView数据
- (void)getData
{

    // 数据
    NSString *str = @"http://www.molyo.com/mIndex/getInfoV1_7";
    NSString *bodyy = [NSString stringWithFormat:@"cityId=%@&currentPage=%ld&netWork=wifi&pageSize=8", self.body, self.MJI];
    
    if (self.body == nil) {
        bodyy = [NSString stringWithFormat:@"cityId=xiamen&currentPage=%ld&netWork=wifi&pageSize=8", self.MJI];
    }
    [HZL_NetworkingHandle requestPOSTWithURl:str body:bodyy completion:^(id result) {
        
        self.hud.hidden = YES;
        if (!result) {
            [self.view bringSubviewToFront:self.alertBtn];
            return;
        }
        
        // 下拉刷新
        if (self.isRefresh) {
            [self.dataArr removeAllObjects];
        }
        // 上拉加载
        
        if ([(NSArray *)result[@"body"][@"subjectList"] count] != 0) {
            [self.dataArr addObjectsFromArray:[HZL_StoreModel transformWithArray:result[@"body"][@"subjectList"]]];
            [self.footer setTitle:@"点击或上拉加载" forState:MJRefreshStateIdle];
        }else {
            // 是否加载完
            [self.footer setTitle:@"已经到底了" forState:MJRefreshStateIdle];
        }
        
        self.alertBtn.hidden = YES;
        [self.hud removeFromSuperview];
        
        [HZL_NetworkingHandle networkReachabilityStatus:^(id r) {
            if (![r isEqualToNumber:@0]) {
                [self.tableView.mj_footer endRefreshing];
            }
        }];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
}
- (void)buttonClick {
    [self getData];
    self.hud.hidden = NO;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HZL_StoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    if (!cell) {
        cell = [[HZL_StoreTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
    }
    cell.model = self.dataArr[indexPath.row];
    
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (VIEW_HEIGHT - 49 - 64) / 2.5;
}
#pragma mark - tableView的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HZL_StateViewController *state = [[HZL_StateViewController alloc] init];
    state.hidesBottomBarWhenPushed = YES;
    state.model = self.dataArr[indexPath.row];
    [self.navigationController pushViewController:state animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
